<template>
  <div v-loading="loading" class="app-container">
    <div class="head-container">
      <div style="display: flex;gap: 10px;">
        <!-- 左卡片 -->
        <el-card class="box-card" style="flex: 7;min-height: 700px;max-height: 700px;overflow-y: scroll;">
          <div style="display: flex;">
            <label class="el-form-item-label">盘点类型</label>
            <el-select v-model="checkInfo.type" placeholder="盘点类型" style="width: 150px;" class="filter-item">
              <el-option
                v-for="item in dict.check_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <label class="el-form-item-label">盘点方式</label>
            <el-select v-model="checkInfo.ways" clearable placeholder="盘点方式" style="width: 150px;" class="filter-item" @change="handlerWayChange">
              <el-option
                v-for="item in dict.check_way"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="!checkInfo.type"
              />
            </el-select>
            <label class="el-form-item-label">母托类型</label>
            <el-select v-model="checkInfo.palletType" clearable placeholder="母托类型" style="width: 150px;" class="filter-item" @change="handlerPalletTypeChange">
              <el-option
                v-for="item in dict.checkPallet_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="checkInfo.ways !=='3'"
              />
            </el-select>
            <label class="el-form-item-label">动碰盘点比例</label>
            <el-select v-model="checkInfo.inventoryPercent" clearable placeholder="动碰盘点比例" style="width: 150px;" class="filter-item">
              <el-option
                v-for="item in dict.check_percent"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="checkInfo.ways !=='4'"
              />
            </el-select>
          </div>
          <div v-if="checkInfo.ways === '4'" style="display: flex;">
            <label class="el-form-item-label">日期</label>
            <el-date-picker
              v-model="selectTime"
              type="datetimerange"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </div>
          <div v-if="productList.length > 0 && checkInfo.ways === '2'">
            <!-- 查询 -->
            <div style="display: flex;">
              <label class="el-form-item-label">物料编号</label>
              <el-input v-model.trim="query.productNo" clearable placeholder="物料编号" style="width: 180px;" class="filter-item" @keyup.enter.native="toQuery" />
              <div style="margin-left: 5px;">
                <el-button size="mini" class="filter-item" icon="el-icon-search" type="success" @click="toQuery">搜索</el-button>
                <el-button size="mini" class="filter-item" icon="el-icon-refresh-right" type="warning" @click="resetQuery">重置</el-button>
              </div>
            </div>
            <el-table
              ref="multipleTable"
              v-loading="listLoading"
              :data="productList"
              style="width: 100%"
              @select="selectProduct"
              @select-all="selectAll"
              @selection-change="handleSelectionChangeLot"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="productNo" label="物料编号" />
              <el-table-column prop="productDescription" label="物料描述" />
            </el-table>
            <!--分页组件-->
            <el-pagination
              :page-size.sync="query.size"
              :total="total"
              :current-page.sync="query.current"
              style="margin-top: 8px;"
              layout="total, prev, pager, next, sizes"
              @size-change="sizeChangeHandler($event)"
              @current-change="pageChangeHandler"
            />
          </div>
        </el-card>
        <!-- 右卡片 -->
        <el-card class="box-card" style="flex: 3;min-height: 700px;max-height: 700px;min-height: 700px;overflow-y: scroll;">
          <div slot="header" class="clearfix" style="display: flex; justify-content: space-between; align-items: center;gap: 10px;">
            <label>Port口</label>
            <el-select v-model="select_portList" multiple collapse-tags clearable placeholder="Port口选择" style="width: 150px;">
              <el-option
                v-for="item in portList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" style="margin-left: auto;" :loading="btn.create" @click="createCheckOrder">创建盘点单</el-button>
          </div>
          <div class="selectTable">
            <div class="right">
              <el-table :data="select_product">
                <el-table-column prop="productNo" label="物料编号" />
                <el-table-column label="操作" width="100px">
                  <template slot-scope="scope">
                    <el-button type="danger" plain size="mini" @click="deleteSelect(scope.row, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
                <div slot="empty" class="empty">
                  <el-empty description="暂无数据" />
                </div>
              </el-table>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getPortListAPI, createOrderAPI, getProductListAPI } from '@/api/work/checkOrder'
export default {
  name: 'CreateCheckOrder',
  dicts: ['checkPallet_type', 'check_type', 'check_way', 'check_percent'],
  data() {
    return {
      query: {
        productNo: '',
        current: 1,
        size: 10
      },
      productList: [],
      select_product: [],
      total: 0,
      selectTime: [],
      checkInfo: {},
      portList: [],
      select_portList: [],
      loading: false,
      listLoading: false,
      btn: {
        create: false
      }
    }
  },
  mounted() {
    this.getPortList()
  },
  methods: {
    // 获取port口list
    async getPortList() {
      try {
        this.loading = true
        const res = await getPortListAPI('portMode')
        if (res.result === 'OK') {
          // console.log(res)
          this.portList = res.data.map(item => {
            return {
              value: item,
              label: item
            }
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 查询库存List
    toQuery() {
      this.query.current = 1
      this.getProductList()
    },
    // 重置
    resetQuery() {
      this.query = {
        productNo: '',
        current: 1,
        size: 10
      }
      this.getProductList()
    },
    // 获取库存list(分页使用)
    async getProductList() {
      try {
        this.listLoading = true
        const res = await getProductListAPI()
        if (res.result === 'OK') {
          this.productList = res.data.content
          this.total = res.data.totalElements
          this.select_product.forEach(item => {
            this.$nextTick(() => {
              this.productList.find(obj => {
                if (item.productNo === obj.productNo) {
                  this.$refs.multipleTable.toggleRowSelection(obj, true)
                }
              })
            })
          })
        } else {
          this.$message.warning(res.data)
          this.table = []
          this.total = 0
        }
      } finally {
        this.listLoading = false
      }
    },
    // 分页相关
    sizeChangeHandler(size) {
      this.query.size = size
      this.query.current = 1
      this.getProductList()
    },
    pageChangeHandler(page) {
      this.query.current = page
      this.getProductList()
    },
    // 第一个框删除逻辑
    // 第二个框删除逻辑
    handlerWayChange() {
      if (!this.checkInfo.ways) {
        this.checkInfo.palletType = ''
        this.checkInfo.inventoryPercent = ''
      }
      if (this.checkInfo.ways === '2') {
        this.toQuery()
      }
    },
    // 第三个框删除逻辑
    handlerPalletTypeChange() {
      if (!this.checkInfo.palletType) {
        this.checkInfo.inventoryPercent = ''
      }
    },
    async createCheckOrder() {
      // 先判断port口是否选择
      if (this.select_portList.length === 0) {
        return this.$message.warning('请选择port口')
      }
      // 母托类型盘点卡控
      if (this.check_way === '3' && !this.checkInfo.palletType) {
        return this.$message.warning('请选择母托类型')
      }
      // 动碰盘点卡控
      if (this.check_way === '4' && !this.checkInfo.inventoryPercent && this.selectTime.length === 0) {
        return this.$message.warning('请选择动碰盘点比例')
      }
      const submitForm = {
        inventoryCheckType: this.checkInfo.type,
        inventoryCheckWay: this.checkInfo.ways,
        palletType: this.checkInfo.palletType,
        inventoryPercent: this.checkInfo.inventoryPercent,
        dynamicTime: this.selectTime,
        sendPortList: this.select_portList,
        productNoList: this.select_product.map(v => v.productNo)
      }
      console.log(submitForm)
      try {
        this.btn.create = true
        const res = await createOrderAPI(submitForm)
        if (res.result === 'OK') {
          this.$message.success('创建成功')
          this.$router.push('/storageManagement/checkOrder')
        } else {
          return this.$message.warning(res.data)
        }
      } finally {
        this.btn.create = false
      }
    },
    // 与右边的产品相关
    selectProduct(selection, row) {
      let a = 0
      selection.forEach(v => {
        if (v.productNo !== row.productNo) {
          a++
        }
      })
      if ((a !== 0 && selection.length !== 0) || (a === 0 && selection.length === 0)) {
        this.select_product.forEach((v, index) => {
          if (v.productNo === row.productNo) {
            this.select_product.splice(index, 1)
          }
        })
      }
    },
    selectAll(val) {
      // 如果取消当前页的全选
      if (val.length === 0) {
        // 筛选出当前列表的所有卷号
        const set2 = new Set(this.productList.map(v => v.productNo))
        // 先把已选择的卷号筛选出来找出已选择中有的但是左边列表里没有的卷号列表
        const a = this.select_product.map(v => v.productNo).filter(item => !set2.has(item))
        // 从已选列表里筛选出上面差异列表里的数据
        const b = this.select_product.filter(v => a.includes(v.productNo))
        this.select_product = b
      }
    },
    handleSelectionChangeLot(val) {
      for (var i = 0; i < val.length; i++) {
        const n = {
          productNo: val[i].productNo
        }
        if (this.select_product.length === 0) {
          this.select_product.push(n)
        } else {
          let a = 0
          for (var j = 0; j < this.select_product.length; j++) {
            if (this.select_product[j].productNo === val[i].productNo) {
              a++
            }
          }
          if (a < 1) {
            this.select_product.push(n)
          }
        }
      }
    },
    deleteSelect(row, index) {
      this.select_product.splice(index, 1)
      this.$nextTick(() => {
        this.productList.find(obj => {
          if (obj.productNo === row.productNo) {
            this.$refs.multipleTable.toggleRowSelection(obj, false)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
